package com.jnu.myfirstapplication;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.google.android.material.navigation.NavigationView;
import com.jnu.myfirstapplication.Adapter.BookRecycleViewAdapter;
import com.jnu.myfirstapplication.data.Book;
import com.jnu.myfirstapplication.data.DataSaver;
import com.jnu.myfirstapplication.data.PicUrl;
import com.jnu.myfirstapplication.recycleItem.ItemTouchCallBack;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class BookListMainActivity extends AppCompatActivity implements BookRecycleViewAdapter.OnItemClickListener{
    static ArrayList<Book> bookList = new ArrayList<>();

    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private ImageView img;//点击该头像 弹出抽屉
    private ImageView headImg;//抽屉里的头像
    private TextView nickName;//用户名
//    private ActionMenuView actionmenuview;


    private EditText mEditText;
    private ImageView mImageView;
    private ListView mListView;
    private TextView mTextView;
    Context context;
    Cursor cursor;

    public static List<Book> mFilterList;                         //过滤后的数组
    public static ArrayList<Integer> bias = new ArrayList<Integer>(); //用于储存一个数组，其表示为每次搜索后每个搜索结果实际位于booklist中的位置

    private List<Book> mList = new ArrayList<>();

    public List<Book> getListBooks() {
        return bookList;
    }

    static ArrayList<ArrayList<Book>> bookShelf = new ArrayList<>();
    //    static ArrayList<Book> bookshelf;
    static ArrayList<String> bookShelfStringArray = new ArrayList<>();
    static HashMap<String, ArrayList<Book>> bookBookShelfHashMap = new HashMap<>();

    static HashMap<String, HashMap<String, ArrayList<Book>>> hashMaps = new HashMap<>();  //表示不同标签的不同书架们


    private String bookShelfName;   //当前书架的名字

    private Spinner bookShelfList; //当前书架列表

    static ArrayList<String> labels = new ArrayList<>();   //存放着所有label的名字
    static String label; //当前的标签
    static int labelId = 0;

    static HashMap<String, HashMap<String, int[]>> eachBookHash = new HashMap<>();   //每本书对应的hash表，用于修改不同标签中的书

    public static int bookCoverNumber = 10;

    public static boolean Toastflag = false;

    @Override
    public void onItemClick(RecyclerView recyclerView, View view, int position, Book obj) {
        Intent intentUpdate = new Intent(this.getApplicationContext(), InputBookItemActivity.class);
        intentUpdate.putExtra("position", position);
        intentUpdate.putExtra("title", mFilterList.get(position).getTitle());
        String testtitle = mFilterList.get(position).getTitle();
        intentUpdate.putExtra("price", mFilterList.get(position).getPrice());
        intentUpdate.putExtra("Author", mFilterList.get(position).getAuthor());
        intentUpdate.putExtra("Translator", mFilterList.get(position).getTranslator());
        intentUpdate.putExtra("Publisher", mFilterList.get(position).getPublisher());
        intentUpdate.putExtra("PubDate", mFilterList.get(position).getPubDate());
        intentUpdate.putExtra("ISBN", mFilterList.get(position).getISBN());
        intentUpdate.putExtra("ReadingState", mFilterList.get(position).getReadingState());
        intentUpdate.putExtra("BookShelf", mFilterList.get(position).getBookShelf());
        intentUpdate.putExtra("Notes", mFilterList.get(position).getNotes());
        intentUpdate.putExtra("Label", mFilterList.get(position).getLabel());
        intentUpdate.putExtra("Website", mFilterList.get(position).getWebsite());
        intentUpdate.putExtra("id", mFilterList.get(position).getCoverResourceId());
//        intentUpdate.putExtra("UUID", mFilterList.get(position).getUuid().toString());
        Bundle bundle = new Bundle();
        intentUpdate.putExtras(bundle);
        updateDataLauncher.launch(intentUpdate);
//        Toast.makeText(getApplicationContext(), obj.getTitle()+"Test", Toast.LENGTH_SHORT).show();
    }


    public class PageViewFragmentAdapter extends FragmentStateAdapter {

        public PageViewFragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            switch (position) {
                case 0:
                    return BookItemFragment.newInstance();
                case 1:
                    return BrowserFragment.newInstance();
                case 2:
                    return MapFragment.newInstance();
                case 3:
                    return GameFragment.newInstance();
            }
            return BookItemFragment.newInstance();
            //return null;
        }

        @Override
        public int getItemCount() {
            return 4;
        }
    }

    @SuppressLint("ResourceType")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_main);
        bookShelfName = "default";
        label = "default";

        ImageView imageVie = findViewById(R.id.delete);
        imageVie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupMenu(imageVie);
                // View当前PopupMenu显示的相对View的位置
                PopupMenu popupMenu = new PopupMenu(getApplicationContext(), view);
                // menu布局
                popupMenu.getMenuInflater().inflate(R.menu.delete, popupMenu.getMenu());
                // menu的item点击事件
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        if (item.getTitle().toString().equals("deleteBookshelf")) {
                            showDialog((String) item.getTitle());
                        } else if (item.getTitle().toString().equals("deleteLabel")) {
                            showDialog((String) item.getTitle());
                            navigationView.setCheckedItem(100);
                        } else if (item.getTitle().toString().equals("renameBookshelf")) {
                            showRenameDialog(item.getTitle().toString());
                        } else if (item.getTitle().toString().equals("renameLabel")) {
                            showRenameDialog(item.getTitle().toString());
                        }
                        return false;
                    }
                });
                // PopupMenu关闭事件
                popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
                    @Override
                    public void onDismiss(PopupMenu menu) {
                    }
                });
                popupMenu.show();
            }
        });

        initbookList();
        scaleAnimation();
        findViews();

        createMenu(findViewById(R.id.navigation_view));
//        ViewPager2 viewPager2Main=findViewById(R.id.viewpager2_main);


        ImageButton add = (ImageButton) findViewById(R.id.fab);
        ImageButton edit1 = findViewById(R.id.edit1);
        ImageButton edit2 = findViewById(R.id.edit2);
        ImageView batchImport = findViewById(R.id.batchImport);
        TextView edit1_context = findViewById(R.id.edit1_context);
        TextView edit2_context = findViewById(R.id.edit2_context);
        TextView batchImport_context = findViewById(R.id.batchImport_context);

        Button search = findViewById(R.id.search);

//        actionmenuview = (ActionMenuView) findViewById(R.id.deleteMenu);
//        actionmenuview.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                Toast.makeText(BookListMainActivity.this,"actionmenuview的点击事件",Toast.LENGTH_SHORT).show();
//                return true;
//            }
//        });


        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edit1.getVisibility() == View.INVISIBLE) {
                    edit1.startAnimation(bigAnimation);
                    edit2.startAnimation(bigAnimation);
//                    batchImport.startAnimation(bigAnimation);
                    edit1.setVisibility(View.VISIBLE);
                    edit2.setVisibility(View.VISIBLE);
//                    batchImport.setVisibility(View.VISIBLE);
                    edit1_context.setVisibility(View.VISIBLE);
                    edit2_context.setVisibility(View.VISIBLE);
//                    batchImport_context.setVisibility(View.VISIBLE);

                } else {
                    edit1.startAnimation(smallAnimation);
                    edit2.startAnimation(smallAnimation);
//                    batchImport.startAnimation(smallAnimation);
                    edit1.setVisibility(View.INVISIBLE);
                    edit2.setVisibility(View.INVISIBLE);
//                    batchImport.setVisibility(View.INVISIBLE);
                    edit1_context.setVisibility(View.INVISIBLE);
                    edit2_context.setVisibility(View.INVISIBLE);
//                    batchImport_context.setVisibility(View.INVISIBLE);
                }
            }
        });
        edit1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog alert = null;
                AlertDialog.Builder builder;
                builder = new AlertDialog.Builder(BookListMainActivity.this);
                alert = builder.setIcon(R.drawable.jinan)
                        .setTitle("系统提示：")
                        .setMessage("选择你想要在扫描图书后执行的操作")
                        .setNegativeButton("扫描图书至本地获取信息", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(BookListMainActivity.this, "你点击了信息按钮~", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(BookListMainActivity.this, QRCodeActivity.class);
                                intent.putExtra("data", "information");
                                startActivityForResult(intent, 111);
                            }
                        })
//                        .setNeutralButton("批量导入", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                Toast.makeText(BookListMainActivity.this, "你点击了批量导入按钮~", Toast.LENGTH_SHORT).show();
//                                Intent intent = new Intent(BookListMainActivity.this, QRCodeActivity.class);
//                                intent.putExtra("data", "batchImport");
//                                startActivityForResult(intent, 111);
//                            }
//                        })
                        .setPositiveButton("图书比价", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(BookListMainActivity.this, "你点击了比价按钮~", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(BookListMainActivity.this, QRCodeActivity.class);
                                intent.putExtra("data", "value");
                                startActivityForResult(intent, 111);
                            }
                        })
                        .setNeutralButton("获取图书评论", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(BookListMainActivity.this, "你点击了评论按钮~", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(BookListMainActivity.this, QRCodeActivity.class);
                                intent.putExtra("data", "comment");
                                startActivityForResult(intent, 111);
                            }
                        }).create();             //创建AlertDialog对象
                alert.show();

            }
        });
        edit2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), InputBookItemActivity.class);
                intent.putExtra("position", 0);
                intent.putExtra("BookShelf", bookShelfStringArray.indexOf(bookShelfName));
                addDataLauncher.launch(intent);
//
//                Intent intent = new Intent(BookListMainActivity.this, CommentPage.class);
//                startActivityForResult(intent, 111);
            }
        });
        batchImport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog alert = null;
                AlertDialog.Builder builder;
                builder = new AlertDialog.Builder(BookListMainActivity.this);
                alert = builder.setIcon(R.drawable.jinan)
                        .setTitle("系统提示：")
                        .setMessage("要批量导入吗？")
                        .setNeutralButton("批量导入", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(BookListMainActivity.this, "你点击了批量导入按钮~", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(BookListMainActivity.this, QRCodeActivity.class);
                                intent.putExtra("data", "batchImport");
                                startActivityForResult(intent, 111);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).create();             //创建AlertDialog对象
                alert.show();
            }
        });

        RecyclerView recycle_view_books = findViewById(R.id.recycleview_main2);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getApplicationContext());
        recycle_view_books.setLayoutManager(linearLayoutManager);


        DataSaver dataSaver = new DataSaver();
        bookList = dataSaver.LoadBookList(this.getApplicationContext());
        InitBookShelf();
        InitBookShelfHashMap();
        initEachBookHashMap();
        initLabels();

        if (hashMaps.size() == 0) {
            HashMap<String, ArrayList<Book>> hashMap = new HashMap();
            hashMap.put("default", new ArrayList<>());
            hashMaps.put("default", hashMap);
        }
        bookBookShelfHashMap = hashMaps.get("default");
        if (bookBookShelfHashMap.size() == 0) {
            bookBookShelfHashMap.put("default", new ArrayList<>());
        }
        if (bookShelfStringArray.size() == 0) {
            bookShelfStringArray.add("default");
            bookShelfStringArray.add("Add New");
        }


//        if (bookBookShelfHashMap.get("default").size() == 0) {
//            bookList.add(new Book("软件项目管理案例教程(第4版)", 0, "1", "1", "1", "1", "1", 0,
//                    0, "1", "1", "1", 0));
//        }


//        bookRecycleViewAdapter = new BookRecycleViewAdapter(bookList);

        bookRecycleViewAdapter = new BookRecycleViewAdapter(getApplicationContext(),bookList);
        bookRecycleViewAdapter.appendList(bookBookShelfHashMap.get("default"));


        ItemTouchCallBack touchCallBack = new ItemTouchCallBack();
        touchCallBack.setOnItemTouchListener(bookRecycleViewAdapter);
//        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(touchCallBack);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback(){
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int swiped = ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT;
                int dragFlags = 0;
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT;
                }else {
                    dragFlags= ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                }
                //第一个参数拖动，第二个删除侧滑
                return makeMovementFlags(dragFlags, swiped);
            }


            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int oldPosition = viewHolder.getAdapterPosition();
                int newPosition = target.getAdapterPosition();
                if(!Toastflag){
                    Toast.makeText(getApplicationContext(),"不允许搜索后更改顺序，这样做也并无意义",Toast.LENGTH_SHORT).show();
                    Toastflag = true;
                }
                if(!bias.isEmpty()){
                    //bias不为空，说明有搜索结果
                    //不允许搜索后更改顺序，这样逻辑很复杂，也没什么实际意义

//                    AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext())
//                            .setTitle("不允许搜索后更改顺序")
//                            .setMessage("这样做也并无意义")
//                            .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialogInterface, int i) {
//                                }
//                            }).create();
//                    alertDialog.show();
                    return false;
                }
                if (oldPosition < newPosition) {
                    for (int i = oldPosition; i < newPosition; i++) {
                        // 改变实际的数据集
                        Collections.swap(mFilterList, i, i +1);

                    }
                } else {
                    for (int i = oldPosition; i > newPosition; i--) {
                        // 改变实际的数据集
                        Collections.swap(mFilterList, i, i - 1);
                    }
                }
//                if(bias!=null){
//                    //不为空，说明有搜索结果，需要更改booklist的位置
//
//                }
                eachBookHash.get(bookBookShelfHashMap.get(bookShelfName).get(oldPosition).getUuid()).put(label,new int[]{bookShelfStringArray.indexOf(bookShelfName),newPosition});
                eachBookHash.get(bookBookShelfHashMap.get(bookShelfName).get(newPosition).getUuid()).put(label,new int[]{bookShelfStringArray.indexOf(bookShelfName),oldPosition});
                bookRecycleViewAdapter.notifyItemMoved(oldPosition, newPosition);
                new DataSaver().save(getApplicationContext(), bookList, bookShelfStringArray);
                new DataSaver().saveHashMap(getApplicationContext(), bookBookShelfHashMap);
                new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
                new DataSaver().saveLabel(getApplicationContext(), labels);
                new DataSaver().saveEachBook(getApplicationContext(), eachBookHash);
                return true;
            }
            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                if(bias.isEmpty()){
                    //为空，说明没有搜索
                    int position = viewHolder.getAdapterPosition();
                    eachBookHash.remove(bookBookShelfHashMap.get(bookShelfName).get(position).getUuid());
                    mFilterList.remove(position);
                    for(int i = position;i<bookBookShelfHashMap.get(bookShelfName).size();i++){
                        eachBookHash.get(bookBookShelfHashMap.get(bookShelfName).get(i).getUuid()).put(label,new int[]{bookShelfStringArray.indexOf(bookShelfName),i});
                    }
//                    bookBookShelfHashMap = hashMaps.get("default");
//                    Book book = bookBookShelfHashMap.get(bookShelfName).get(position);

//                    bookBookShelfHashMap.get(bookShelfName).remove(position);
//                    bookRecycleViewAdapter.notifyItemRemoved(position);
                    new DataSaver().save(getApplicationContext(), bookList, bookShelfStringArray);
                    new DataSaver().saveHashMap(getApplicationContext(), bookBookShelfHashMap);
                    new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
                    new DataSaver().saveLabel(getApplicationContext(), labels);
                    new DataSaver().saveEachBook(getApplicationContext(), eachBookHash);
                }else{
                    int position = viewHolder.getAdapterPosition();
                    mFilterList.remove(position);
                    eachBookHash.remove(bookBookShelfHashMap.get(bookShelfName).get(bias.get(position)).getUuid());
                    ArrayList<Book> testBookList = bookBookShelfHashMap.get(bookShelfName);
                    //必须这样加临时变量然后下面再删除，直接调用就是他妈的不行，唉
                    int real = bias.get(position);
                    bookBookShelfHashMap.get(bookShelfName).remove(real);
                    bookRecycleViewAdapter.notifyItemRemoved(position);
                    new DataSaver().save(getApplicationContext(), bookList, bookShelfStringArray);
                    new DataSaver().saveHashMap(getApplicationContext(), bookBookShelfHashMap);
                    new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
                    new DataSaver().saveLabel(getApplicationContext(), labels);
                    new DataSaver().saveEachBook(getApplicationContext(), eachBookHash);
                }


//                new DataSaver().save(getApplicationContext(), bookList, bookShelfStringArray);
//                new DataSaver().saveHashMap(getApplicationContext(), bookBookShelfHashMap);
//                new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
//                new DataSaver().saveLabel(getApplicationContext(), labels);
//                new DataSaver().saveEachBook(getApplicationContext(), eachBookHash);
            }
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState!=ItemTouchHelper.ACTION_STATE_IDLE){
                    viewHolder.itemView.setBackgroundColor(Color.parseColor("#33FF66"));
                }
            }
            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT);
            }
        });
        itemTouchHelper.attachToRecyclerView(recycle_view_books);

//        recycle_view_books.setLayoutManager(new GridLayoutManager(this,3));

        recycle_view_books.setAdapter(bookRecycleViewAdapter);
        itemTouchHelper.attachToRecyclerView(recycle_view_books);
        bookRecycleViewAdapter.setOnItemClickListener(this);






        EditText et = findViewById(R.id.edittext);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence sequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence sequence, int i, int i1, int i2) {
                bookRecycleViewAdapter.getFilter().filter(sequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        bookShelfList = findViewById(R.id.bookShelfList);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (et.getVisibility() == View.VISIBLE) {
                    et.setVisibility(View.INVISIBLE);
                    bookShelfList.setVisibility(View.VISIBLE);
                } else {
                    et.setVisibility(View.VISIBLE);
                    bookShelfList.setVisibility(View.INVISIBLE);
                }
            }
        });

        ArrayList<String> temp = new ArrayList<>();
//        temp.remove(temp.size()-1); //这里把最后一个Add New 去掉了,直接赋值等于的话因为是浅拷贝结果把原来的也弄掉了...只能new一个深拷贝了，真蛋疼
        for (int i = 0; i < bookShelfStringArray.size() - 1; i++) {
            temp.add(bookShelfStringArray.get(i));
        }
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, temp);
        bookShelfList.setAdapter(adapter);

        bookShelfList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //
                String info = adapterView.getItemAtPosition(i).toString();//获取i所在的文本
                bookShelfName = info;
                ArrayList<Book> temp = bookBookShelfHashMap.get(info);
                bookRecycleViewAdapter.appendList(bookBookShelfHashMap.get(info));
//                Toast.makeText(BookListMainActivity.this, info, Toast.LENGTH_SHORT).show();
                mFilterList = bookBookShelfHashMap.get(info);
                bookRecycleViewAdapter.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        //不要标题栏了（因为标题栏的 NavigationIcon不容易改，所以我们主页面自己画了）


        /**
         * 头像的动态设置，因为每个用户的头像都不一样，所以这不能在xml里写死
         * headView非常有必要，因为Android的findViewById一般找不到更深层布局的视图
         * 所以要想动态修改抽屉里头部（head_view.xml）的控件，必须通过headView
         */
        View headView = navigationView.getHeaderView(0);//get hedaView
        headImg = headView.findViewById(R.id.userHeadImg);//不通过headView找不到
        //设置昵称
        nickName = headView.findViewById(R.id.nickName);
        nickName.setText("BookShelf");

//
        img = findViewById(R.id.menu);
        //点击头像划出测边框
        img.setOnClickListener(v -> {
            if (drawerLayout.isDrawerOpen(navigationView)) {
                drawerLayout.closeDrawer(navigationView);
            } else {
                drawerLayout.openDrawer(navigationView);
            }
        });

        navigationView.setNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case 100://个人
                    drawerLayout.closeDrawer(navigationView);
                    bookBookShelfHashMap = hashMaps.get("default");
                    bookRecycleViewAdapter.appendList(bookBookShelfHashMap.get(bookShelfName));
                    bookRecycleViewAdapter.notifyDataSetChanged();
                    item.setCheckable(true);
                    label = "default";
                    break;
                case 101://搜索
                    et.setVisibility(View.VISIBLE);
                    bookShelfList.setVisibility(View.INVISIBLE);
                    drawerLayout.closeDrawer(navigationView);
                    break;
                case 102:
                    try {
                        EditText editText = new EditText(this);
                        AlertDialog alertDialog = new AlertDialog.Builder(this)
                                .setTitle(R.string.string_confirmation)
                                .setMessage("添加标签吗？")
                                .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                    }
                                }).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        labels.add(editText.getText().toString());
                                        new DataSaver().saveLabel(getApplicationContext(), labels);
                                        HashMap<String, ArrayList<Book>> hp = new HashMap<>();
                                        for (String string : bookShelfStringArray) {
                                            hp.put(string, new ArrayList<>());
                                        }
                                        hashMaps.put(editText.getText().toString(), hp);
                                        navigationView.getMenu().add(1, editText.getText().toString().hashCode(), 0, "    " + editText.getText()).setIcon(R.drawable.ic_label);//需要获取id的话，id就等于1；
                                        new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
                                    }
                                }).setView(editText)
                                .create();
                        alertDialog.show();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 103://设置
                    drawerLayout.closeDrawer(navigationView);
                    startActivityForResult(new Intent(BookListMainActivity.this, Setting.class), 200);
                    break;
                case 104:
                    drawerLayout.closeDrawer(navigationView);
                    startActivityForResult(new Intent(BookListMainActivity.this, About.class), 200);
                    break;
                case 105:
                    Uri uri = Uri.parse("https://m.douban.com/home_guide");
                    startActivity(new Intent(Intent.ACTION_VIEW,uri));
                    break;
                default:
                    drawerLayout.closeDrawer(navigationView);
                    bookBookShelfHashMap = hashMaps.get(item.toString().trim());
                    bookRecycleViewAdapter.appendList(bookBookShelfHashMap.get(bookShelfName));
                    bookRecycleViewAdapter.notifyDataSetChanged();
                    System.out.println(hashMaps);
                    item.setCheckable(true);
                    label = item.toString().trim();
                    labelId = item.getItemId();
            }
            return true;
        });
//        navigationView.setCheckedItem(100);
//        navigationView.getMenu().getItem(0).setChecked(true);
//        navigationView.getMenu().setGroupEnabled(100,true);
//        navigationView.getMenu().setGroupCheckable(0,true,true);
        System.out.println(bookBookShelfHashMap);
        System.out.println(bookShelfStringArray);
    }


    private void findViews() {
        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.navigation_view);
        img = findViewById(R.id.img);
    }


    private static final int MENU_ID_ADD = 1;
    private static final int MENU_ID_UPDATE = 2;
    private static final int MENU_ID_DELETE = 3;
    private BookRecycleViewAdapter bookRecycleViewAdapter;
    int id;

    static ArrayList<Integer> mArray = new ArrayList<Integer>() {{
        add(R.drawable.book_1);
        add(R.drawable.book_2);
        add(R.drawable.book_no_name);
        add(R.drawable.jidushan);
        add(R.drawable.brother);
        add(R.drawable.live);
        add(R.drawable.ming);
        add(R.drawable.summer);
        add(R.drawable.tired);
        add(R.drawable.war);
        add(R.drawable.western);
    }};

    private ActivityResultLauncher<Intent> addDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (null != result) {
                    Intent intent = result.getData();
                    if (result.getResultCode() == InputBookItemActivity.RESULT_CODE_SUCCESS) {
                        Bundle bundle = intent.getExtras();
                        String title = bundle.getString("title");
                        String Author = bundle.getString("Author");
                        String Translator = bundle.getString("Translator");
                        String Publisher = bundle.getString("Publisher");
                        String PubDate = bundle.getString("PubDate");
                        String ISBN = bundle.getString("ISBN");
                        int ReadingState = bundle.getInt("ReadingState");
                        int BookShelf = bundle.getInt("BookShelf");
                        String Notes = bundle.getString("Notes");
                        String Label = bundle.getString("Label");
                        String Website = bundle.getString("Website");
                        id = bundle.getInt("id");
                        int position = bundle.getInt("position");
                        String uuid = bundle.getString("UUID");
//                        bookBookShelfHashMap.get(bookShelfStringArray.get(BookShelf)).add(position, new Book(title, id,Author,Translator,Publisher,PubDate,ISBN,ReadingState,BookShelf,
//                                Notes,Label,Website));
                        String test = bookShelfName;

                        int temp = bookBookShelfHashMap.get(bookShelfName).size();
                        int thisBookPosition = bookBookShelfHashMap.get(bookShelfStringArray.get(BookShelf)).size();  //得到这本书在对应书架的booklist的位置

                        Book book = new Book(title, id, Author, Translator, Publisher, PubDate, ISBN, ReadingState, BookShelf,
                                Notes, Label, Website,
                                thisBookPosition);
                        book.setUuid(bundle.getString("UUID"));
                        int[] bookPosition = {BookShelf, BookListMainActivity.hashMaps.get(label).get(bookShelfStringArray.get(BookShelf)).size()};
                        HashMap<String, int[]> hashMap = new HashMap();
                        hashMap.put(label, bookPosition);
                        eachBookHash.put(uuid, hashMap);
//                        bookBookShelfHashMap = hashMaps.get("default");
                        bookBookShelfHashMap.get(bookShelfStringArray.get(BookShelf)).add(book);

                        if (bias.size() != 0) {
                            //深拷贝
                            mFilterList.add(position, new Book(title, id, Author, Translator, Publisher, PubDate, ISBN, ReadingState, BookShelf,
                                    Notes, Label, Website, thisBookPosition));
                            if (temp != bookBookShelfHashMap.get(bookShelfName).size()) {
                                //增加前后当前书架长度不一样，说明是增加的这个书架的书而非别的书架
                                for (int i = 0; i < bias.size(); i++) {
                                    bias.set(i, bias.get(i) + 1);  //先对后面的值进行操作
                                }
                                bias.add(0, 0);//然后在bias头部插入位置为0
                            } else {
                                //增加的别的书架，对bias就不处理了
                            }

                        }

                        //这里显示的还是过滤后的数组，没有对过滤后数组添加就进行刷新的话就会报错...
//                        bookRecycleViewAdapter.notifyItemInserted(position);
                        bookRecycleViewAdapter.notifyDataSetChanged();

                        new DataSaver().save(this.getApplicationContext(), bookList, bookShelfStringArray);
//                        new DataSaver().saveHashMap(this.getApplicationContext(), bookBookShelfHashMap);
                        new DataSaver().saveHashMaps(this.getApplicationContext(), hashMaps);
                        new DataSaver().saveLabel(this.getApplicationContext(), labels);
                        new DataSaver().saveEachBook(this.getApplicationContext(), eachBookHash);

                    }
                }
            });
    private Animation bigAnimation, smallAnimation;

    private void scaleAnimation() {
        //放大
        bigAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale_big);
        //缩小
        smallAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale_small);
    }

    private ActivityResultLauncher<Intent> updateDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (null != result) {
                    Intent intent = result.getData();
                    if (result.getResultCode() == InputBookItemActivity.RESULT_CODE_SUCCESS) {
                        Bundle bundle = intent.getExtras();
                        String title = bundle.getString("title");
                        Double price = bundle.getDouble("price");
                        int position = bundle.getInt("position");
                        String Author = bundle.getString("Author");
                        String Translator = bundle.getString("Translator");
                        String Publisher = bundle.getString("Publisher");
                        String PubDate = bundle.getString("PubDate");
                        String ISBN = bundle.getString("ISBN");
                        int ReadingState = bundle.getInt("ReadingState");
                        int BookShelf = bundle.getInt("BookShelf");
                        String Notes = bundle.getString("Notes");
                        String Label = bundle.getString("Label");
                        String Website = bundle.getString("Website");
                        int id = bundle.getInt("id");
                        String uuid = bundle.getString("UUID");

//                        if(bias.size()==0){
//                            //没有进行搜索或者搜索结果为0
//                            bookList.get(position).setTitle(title);
//                            bookList.get(position).setPrice(price);
//                            bookList.get(position).setAuthor(Author);
//                            bookList.get(position).setTranslator(Translator);
//                            bookList.get(position).setPublisher(Publisher);
//                            bookList.get(position).setPubDate(PubDate);
//                            bookList.get(position).setISBN(ISBN);
//                            bookList.get(position).setReadingState(ReadingState);
//                            bookList.get(position).setBookShelf(BookShelf);
//                            bookList.get(position).setNotes(Notes);
//                            bookList.get(position).setLabel(Label);
//                            bookList.get(position).setWebsite(Website);
//                            bookList.get(position).setId(id);
//                            bookBookShelfHashMap.get(bookShelfStringArray.get(BookShelf)).add(new Book(title, id,Author,Translator,Publisher,PubDate,ISBN,ReadingState,BookShelf,
//                                    Notes,Label,Website));
//                        }else{
//                            //进行了搜索
//                            bookList.get(bias.get(position)).setTitle(title);
//                            bookList.get(bias.get(position)).setPrice(price);
//                            bookList.get(bias.get(position)).setAuthor(Author);
//                            bookList.get(bias.get(position)).setTranslator(Translator);
//                            bookList.get(bias.get(position)).setPublisher(Publisher);
//                            bookList.get(bias.get(position)).setPubDate(PubDate);
//                            bookList.get(bias.get(position)).setISBN(ISBN);
//                            bookList.get(bias.get(position)).setReadingState(ReadingState);
//                            bookList.get(bias.get(position)).setBookShelf(BookShelf);
//                            bookList.get(bias.get(position)).setNotes(Notes);
//                            bookList.get(bias.get(position)).setLabel(Label);
//                            bookList.get(bias.get(position)).setWebsite(Website);
//                            bookList.get(bias.get(position)).setId(id);
//                        }
                        System.out.println(bookList);
                        System.out.println(bookBookShelfHashMap.get("书架2"));
                        mFilterList.get(position).setTitle(title);
                        mFilterList.get(position).setPrice(price);
                        mFilterList.get(position).setAuthor(Author);
                        mFilterList.get(position).setTranslator(Translator);
                        mFilterList.get(position).setPublisher(Publisher);
                        mFilterList.get(position).setPubDate(PubDate);
                        mFilterList.get(position).setISBN(ISBN);
                        mFilterList.get(position).setReadingState(ReadingState);
                        mFilterList.get(position).setNotes(Notes);
                        mFilterList.get(position).setLabel(Label);
                        mFilterList.get(position).setWebsite(Website);
                        mFilterList.get(position).setId(id);
                        //这个只能最后处理，不然其他信息的position就出错了
                        int temp = mFilterList.get(position).getBookShelf();

                        if (temp == BookShelf) {
                            //在这时候进行判断前后是否改变了书架
                            //不判断的话，每次更新都会在那个书架加这样一本书...
                        } else {
                            //过滤后的的数组的位置应该和每个列表的位置是一样的，直接移除position就行了吧
                            mFilterList.get(position).setBookShelf(BookShelf);  //先移除再设置的话会有问题...要放在最上面
                            //只能用temp来保存一下了，不然有问题
                            if (bias.size() == 0) {
                                //没有搜索结果，视为浅拷贝，只删除一次
                                bookBookShelfHashMap.get(bookShelfStringArray.get(temp)).remove(position);//移除旧的书，一本书只能在一个书架里，但怎么获取这本书在这个书架列表中的位置呢...
//
//                                eachBookHash.get(uuid).get(label)[0]=BookShelf;
//
//                                eachBookHash.get(uuid).get(label)[1]=;
                            } else {
                                mFilterList.remove(position);   //mFilterList是深拷贝...这里也要移除么..但如果没有搜索结果就是浅拷贝了
                                ArrayList<Book> test = bookBookShelfHashMap.get(bookShelfStringArray.get(temp));
                                int value = bias.get(position);
                                test.remove(value);     //remove写死是1就可以，上面的value却不行？？...应该是作为object来remove了，不会这么蠢吧
                                //bug不能复现，我操你妈操你妈操你妈操你妈操你妈操你妈操你妈操你妈操你妈操你妈操你妈操你妈操你妈
//                                System.out.println(test); //明明这几行和下面应该是等价的，却非要分开写不然就有问题，真是操蛋
//                                bookBookShelfHashMap.get(bookShelfStringArray.get(temp)).remove(bias.get(position));//移除旧的书，一本书只能在一个书架里，但怎么获取这本书在这个书架列表中的位置呢...
                            }
                            int thisBookPosition = bookBookShelfHashMap.get(bookShelfStringArray.get(BookShelf)).size();  //得到这本书在对应书架的booklist的位置
                            Book book = new Book(title, id, Author, Translator, Publisher, PubDate, ISBN, ReadingState, BookShelf,
                                    Notes, Label, Website, thisBookPosition);
                            book.setUuid(uuid);
                            bookBookShelfHashMap.get(bookShelfStringArray.get(BookShelf)).add(book);
                            eachBookHash.get(uuid).get(label)[0] = BookShelf; //更新eachbook 的hashmap的值
                            eachBookHash.get(uuid).get(label)[1] = thisBookPosition;
                        }
                        bookRecycleViewAdapter.notifyDataSetChanged();
//                        bookRecycleViewAdapter.notifyItemChanged(position);     //这里无论是有无进行搜索，改变的都是实际显示的位置position

                        new DataSaver().save(this.getApplicationContext(), bookList, bookShelfStringArray);
                        new DataSaver().saveHashMap(this.getApplicationContext(), bookBookShelfHashMap);
                        new DataSaver().saveHashMaps(this.getApplicationContext(), hashMaps);
                        new DataSaver().saveLabel(this.getApplicationContext(), labels);
                        new DataSaver().saveEachBook(getApplicationContext(), eachBookHash);
                    }
                }
            });


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment BookItemFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BookItemFragment newInstance() {
        BookItemFragment fragment = new BookItemFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
//            case MENU_ID_ADD:
//                Intent intent = new Intent(this.getApplicationContext(), InputBookItemActivity.class);
//                intent.putExtra("position",item.getOrder());
//                intent.putExtra("BookShelf",bookShelfStringArray.indexOf(bookShelfName));
//                addDataLauncher.launch(intent);
//                break;
            case MENU_ID_UPDATE:
                Intent intentUpdate = new Intent(this.getApplicationContext(), InputBookItemActivity.class);
                intentUpdate.putExtra("position", item.getOrder());
//                if(bias.size()==0){
//                    //如果为0表示没有进行搜索或搜索结果为空
//
//                    //优化直接传对象过去，不再一个个传值了 必须从这里动手改了，这样就再也不用bias这个sbin的方法了
////                    Bundle bundle = new Bundle();
////                    bundle.putSerializable("Book", bookList.get(item.getOrder()));
////                    intentUpdate.putExtras(bundle);
//
//                    intentUpdate.putExtra("title",mFilterList.get(item.getOrder()).getTitle());
//                    intentUpdate.putExtra("price",mFilterList.get(item.getOrder()).getPrice());
//                    intentUpdate.putExtra("Author",mFilterList.get(item.getOrder()).getAuthor());
//                    intentUpdate.putExtra("Translator",mFilterList.get(item.getOrder()).getTranslator());
//                    intentUpdate.putExtra("Publisher",mFilterList.get(item.getOrder()).getPublisher());
//                    intentUpdate.putExtra("PubDate",mFilterList.get(item.getOrder()).getPubDate());
//                    intentUpdate.putExtra("ISBN",mFilterList.get(item.getOrder()).getISBN());
//                    intentUpdate.putExtra("ReadingState",mFilterList.get(item.getOrder()).getReadingState());
//                    intentUpdate.putExtra("BookShelf",mFilterList.get(item.getOrder()).getBookShelf());
//                    intentUpdate.putExtra("Notes",mFilterList.get(item.getOrder()).getNotes());
//                    intentUpdate.putExtra("Label",mFilterList.get(item.getOrder()).getLabel());
//                    intentUpdate.putExtra("Website",mFilterList.get(item.getOrder()).getWebsite());
//                    intentUpdate.putExtra("id",mFilterList.get(item.getOrder()).getCoverResourceId());
//                }else{
//                    //表示有搜索结果
//                    ArrayList<Book> test=bookList;
//                    intentUpdate.putExtra("title",bookList.get(bias.get(item.getOrder())).getTitle());
//                    intentUpdate.putExtra("price",bookList.get(bias.get(item.getOrder())).getPrice());
//                    intentUpdate.putExtra("Author",bookList.get(bias.get(item.getOrder())).getAuthor());
//                    intentUpdate.putExtra("Translator",bookList.get(bias.get(item.getOrder())).getTranslator());
//                    intentUpdate.putExtra("Publisher",bookList.get(bias.get(item.getOrder())).getPublisher());
//                    intentUpdate.putExtra("PubDate",bookList.get(bias.get(item.getOrder())).getPubDate());
//                    intentUpdate.putExtra("ISBN",bookList.get(bias.get(item.getOrder())).getISBN());
//                    intentUpdate.putExtra("ReadingState",bookList.get(bias.get(item.getOrder())).getReadingState());
//                    intentUpdate.putExtra("BookShelf",bookList.get(bias.get(item.getOrder())).getBookShelf());
//                    intentUpdate.putExtra("Notes",bookList.get(bias.get(item.getOrder())).getNotes());
//                    intentUpdate.putExtra("Label",bookList.get(bias.get(item.getOrder())).getLabel());
//                    intentUpdate.putExtra("Website",bookList.get(bias.get(item.getOrder())).getWebsite());
//                    intentUpdate.putExtra("id",bookList.get(bias.get(item.getOrder())).getCoverResourceId());
//                }

                intentUpdate.putExtra("title", mFilterList.get(item.getOrder()).getTitle());
                String testtitle = mFilterList.get(item.getOrder()).getTitle();
                intentUpdate.putExtra("price", mFilterList.get(item.getOrder()).getPrice());
                intentUpdate.putExtra("Author", mFilterList.get(item.getOrder()).getAuthor());
                intentUpdate.putExtra("Translator", mFilterList.get(item.getOrder()).getTranslator());
                intentUpdate.putExtra("Publisher", mFilterList.get(item.getOrder()).getPublisher());
                intentUpdate.putExtra("PubDate", mFilterList.get(item.getOrder()).getPubDate());
                intentUpdate.putExtra("ISBN", mFilterList.get(item.getOrder()).getISBN());
                intentUpdate.putExtra("ReadingState", mFilterList.get(item.getOrder()).getReadingState());
                intentUpdate.putExtra("BookShelf", mFilterList.get(item.getOrder()).getBookShelf());
                intentUpdate.putExtra("Notes", mFilterList.get(item.getOrder()).getNotes());
                intentUpdate.putExtra("Label", mFilterList.get(item.getOrder()).getLabel());
                intentUpdate.putExtra("Website", mFilterList.get(item.getOrder()).getWebsite());
                intentUpdate.putExtra("id", mFilterList.get(item.getOrder()).getCoverResourceId());
                intentUpdate.putExtra("UUID", mFilterList.get(item.getOrder()).getUuid().toString());
                Bundle bundle = new Bundle();
                intentUpdate.putExtras(bundle);
                updateDataLauncher.launch(intentUpdate);
                break;
            case MENU_ID_DELETE:
                try {
                    String uuid = mFilterList.get(item.getOrder()).getUuid().toString();
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(R.string.string_confirmation)
                            .setMessage(R.string.string_sure_to_delete)
                            .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            }).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    if (bias.size() == 0) {
                                        //如果为0表示没有进行搜索或搜索结果为空
                                        bookBookShelfHashMap.get(bookShelfName).remove(item.getOrder());
                                        eachBookHash.get(uuid).remove(label);   //直接移除掉eachbook里面的label标签
                                    } else {
                                        int index = bias.get(item.getOrder());
//                                        bookList.remove(bias.get(item.getOrder()));   //直接这样是没办法删除的...必须先用index获取了再执行下面的才能删除...不知道为什么
                                        bookBookShelfHashMap.get(bookShelfName).remove(index);
                                        mFilterList.remove(item.getOrder());
                                        bias.remove(item.getOrder());
                                        for (int j = item.getOrder(); j < bias.size(); j++) { //删除的是搜索后的后面的元素，所以需要+1,也可以先移除，这样就不用+1了，这里采取了先移除
                                            bias.set(j, bias.get(j) - 1);
                                        }
                                    }
                                    new DataSaver().save(getApplicationContext(), bookList, bookShelfStringArray);
                                    //还需要删除过滤后的数组mFilterList的，因为这时候显示的还是该数组
                                    bookRecycleViewAdapter.notifyItemRemoved(item.getOrder());  ////这里无论是有无进行搜索，改变的都是实际显示的位置position
                                }
                            }).create();
                    alertDialog.show();
                    new DataSaver().save(getApplicationContext(), bookList, bookShelfStringArray);
                    new DataSaver().saveHashMap(getApplicationContext(), bookBookShelfHashMap);
                    new DataSaver().saveEachBook(getApplicationContext(), eachBookHash);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
        return super.onContextItemSelected(item);
    }

    private void initbookList() {
//        bookList.add(new Book("软件项目管理案例教程(第4版)", R.drawable.book_2,100));
//        bookList.add(new Book("创新工程实践", R.drawable.book_no_name,200));
//        bookList.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1,300));
    }


    public static boolean isDarkTheme(Context context) {
        int flag = context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
        return flag == Configuration.UI_MODE_NIGHT_YES;
    }

    public class photoThread implements Runnable{
        String photoUrl;
        public photoThread(String photoUrl){this.photoUrl=photoUrl;}
        @Override
        public void run() {
            try {
                PicUrl picUrl = new PicUrl();
                Bitmap bitmap = picUrl.returnBitMap(photoUrl);
                if (bitmap != null) {
                    bookCoverNumber++;  //bookCoverNumber+1并保存
                    picUrl.saveImg(bitmap, "/sdcard/Pictures/book/", "book" + bookCoverNumber);
                    new DataSaver().saveBookCoverNumber(getApplicationContext(), bookCoverNumber);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
//            navigationView.setCheckedItem(R.id.item_personal);
        }
        if (resultCode == InputBookItemActivity.RESULT_CODE_SUCCESS) {
            //InputBookItemActivity.RESULT_CODE_SUCCESS 代表已经从InputBookItemActivity成功返回，要刷新booklist和书架之类的
            bookList = new DataSaver().LoadBookList(this.getApplicationContext());
            bookShelfStringArray = new DataSaver().LoadBookShelfName(this.getApplicationContext());
        }
        switch (resultCode) {
            case 200:
                if (resultCode == 200) {
//                    String returnData = data.getStringExtra("data_return");
//                    Log.d("FirstActivity",returnData);
//                    Toast.makeText(BookListMainActivity.this,"return 200",Toast.LENGTH_LONG).show();
                }
//                Toast.makeText(BookListMainActivity.this,"return 200",Toast.LENGTH_LONG).show();
                break;
            case 201:
                //用201代表要更新书架列表
                ArrayList<String> temp = new ArrayList<>();
                for (int i = 0; i < bookShelfStringArray.size() - 1; i++) {
                    temp.add(bookShelfStringArray.get(i));
                }
                ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, temp);
                bookShelfList.setAdapter(adapter);
                bookRecycleViewAdapter.notifyDataSetChanged();
                break;
            case 500:
                //用500来表示扫描回来了data
                String title = data.getStringExtra("title");
                String author = data.getStringExtra("author");
                String publisher = data.getStringExtra("publisher");
                String notes = data.getStringExtra("notes");
                String Translator = data.getStringExtra("translator");
                String ISBN = data.getStringExtra("ISBN");
                String photoUrl = data.getStringExtra("photoUrl");
                String website = data.getStringExtra("website");

                Intent intent = new Intent(getApplicationContext(), InputBookItemActivity.class);
                intent.putExtra("position", 0);
                intent.putExtra("title", title);
                intent.putExtra("Author", author);
                intent.putExtra("Publisher", publisher);
                intent.putExtra("Notes", notes);
                intent.putExtra("Translator", Translator);
                intent.putExtra("ISBN", ISBN);
                intent.putExtra("Website", website);

                intent.putExtra("BookShelf", bookShelfStringArray.indexOf(bookShelfName));

//                intent.putExtra("id",mArray.size());

                if (photoUrl.length() > 0) {
                    //正确返回url了才保存
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//
//                        }
//                    }).start();
                    try{
                        Thread thread = new Thread(new photoThread(photoUrl));
                        thread.start();
                        thread.join();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                intent.putExtra("id", bookCoverNumber);
                addDataLauncher.launch(intent);
        }
    }

    public void InitBookShelf() {
        bookShelfStringArray = new DataSaver().LoadBookShelfName(this.getApplicationContext());
        if (bookShelfStringArray.size() == 0) {
            for (String string : getResources().getStringArray(R.array.BookShelf)) {
                //获取资源里所有静态变量，然后将其加入这个string数组
                BookListMainActivity.bookShelfStringArray.add(string);
            }
        }
    }

    public void InitBookShelfHashMap() {
//        ArrayList<Book> defaultBookList=new ArrayList<>();
//        for(Book book:bookList){
//            defaultBookList.add(book);
//        }
//        bookBookShelfHashMap.put("书架1",defaultBookList);
//        for(int i=1;i<bookShelfStringArray.size();i++){
//            bookBookShelfHashMap.put(bookShelfStringArray.get(i),new ArrayList<Book>());
//        }
//        for(int i=0;i<bookList.size();i++){    //这里如果用Book book:bookList的方法的话就会因为又对位于1位置的booklist进行添加最后导致循环报错....要么下面进行判断如果是default就不加，要么就用i<size的方式进行循环
//            String test=bookShelfStringArray.get(bookList.get(i).getBookShelf());
//            if(test.equals("书架1")!=true){
//                defaultBookList.remove(i);
//                bookBookShelfHashMap.get(bookShelfStringArray.get(bookList.get(i).getBookShelf())).add(bookList.get(i));
//            }
//        }
        bookBookShelfHashMap = new DataSaver().LoadHashMap(this.getApplicationContext());
        bookShelfStringArray = new DataSaver().LoadBookShelfName(this.getApplicationContext());
    }


    private void showPopupMenu(View view) {

    }

    private void showDialog(String name) {
        try {
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle(R.string.string_confirmation)
                    .setMessage("Are you sure to delete this " + name.substring(6) + "?")
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            System.out.println(bookShelfStringArray);

//                            new DataSaver().save(getApplicationContext(),bookList,bookShelfStringArray);
//                            new DataSaver().saveHashMap(getApplicationContext(),bookBookShelfHashMap);
                        }
                    }).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (name.equals("deleteBookshelf")) {
                                if (!bookShelfName.equals("default")) {
                                    bookBookShelfHashMap.remove(bookShelfName);
                                    int x = bookShelfStringArray.indexOf(bookShelfName);
                                    bookShelfStringArray.remove(x);
                                    ArrayList<String> temp = new ArrayList<>();
                                    for (int j = 0; j < bookShelfStringArray.size() - 1; j++) {
                                        temp.add(bookShelfStringArray.get(j));
                                    }
                                    ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, temp);
                                    bookShelfList.setAdapter(adapter);
                                    bookRecycleViewAdapter.notifyDataSetChanged();
                                    new DataSaver().save(getApplicationContext(), bookList, bookShelfStringArray);
                                    new DataSaver().saveHashMap(getApplicationContext(), bookBookShelfHashMap);
                                    new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
                                } else {
                                    Toast.makeText(BookListMainActivity.this, "Can not remove default bookshelf!", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            } else if (name.equals("deleteLabel")) {
                                if (!label.equals("default")) {
                                    navigationView.getMenu().removeItem(label.hashCode());
                                    labels.remove(label);
                                    navigationView.refreshDrawableState();
                                    hashMaps.remove(label);
                                    eachBookHash.forEach((key, value) -> {
                                        value.remove(label);
                                    });
                                    //需要获取id的话，id就等于1；
                                } else {
                                    Toast.makeText(getApplicationContext(), "Can not remove default label!", Toast.LENGTH_SHORT).show();
                                }
                                System.out.println(navigationView);
                                new DataSaver().saveLabel(getApplicationContext(), labels);
                                new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
                                new DataSaver().saveEachBook(getApplicationContext(), eachBookHash);
                            }
//                            navigationView.setCheckedItem(0);
                        }
                    }).create();
            alertDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showRenameDialog(String name) {
        if (name.equals("renameBookshelf")) {
            try {
                if (bookShelfName.equals("default")) {
                    Toast.makeText(getApplicationContext(), "can not rename default bookshelf!", Toast.LENGTH_SHORT).show();
                    return;
                }
                EditText editText = new EditText(BookListMainActivity.this);
                AlertDialog alertDialog = new AlertDialog.Builder(BookListMainActivity.this)
                        .setTitle(R.string.string_confirmation)
                        .setMessage("请输入新" + name.substring(6) + "名")
                        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                for (String string : bookShelfStringArray) {
                                    if (string.equals(editText.getText().toString())) {
                                        Toast.makeText(getApplicationContext(), "Can not rename bookshelf same with exist bookshelf!", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                }
                                int x = bookShelfStringArray.indexOf(bookShelfName);
                                bookShelfStringArray.remove(x);
                                bookShelfStringArray.add(x, editText.getText().toString());
                                hashMaps.forEach((key, value) -> {
                                    ArrayList<Book> temp = value.get(bookShelfName);
                                    value.remove(bookShelfName);
                                    value.put(editText.getText().toString(), temp);
                                });
                                bookShelfName = editText.getText().toString();
                                ArrayList<String> temp = new ArrayList<>();
                                for (int j = 0; j < bookShelfStringArray.size() - 1; j++) {
                                    temp.add(bookShelfStringArray.get(j));
                                }
                                ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, temp);
                                bookShelfList.setAdapter(adapter);
                                bookRecycleViewAdapter.notifyDataSetChanged();
                                new DataSaver().save(getApplicationContext(), bookList, bookShelfStringArray);
                                new DataSaver().saveHashMap(getApplicationContext(), bookBookShelfHashMap);
                                new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
                                Toast.makeText(getApplicationContext(), editText.getText(), Toast.LENGTH_SHORT).show();
                            }
                        }).setView(editText)
                        .create();
                alertDialog.show();

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (name.equals("renameLabel")) {
            try {
                if (label.equals("default")) {
                    Toast.makeText(getApplicationContext(), "can not rename default label!", Toast.LENGTH_SHORT).show();
                    return;
                }
                EditText editText = new EditText(BookListMainActivity.this);
                AlertDialog alertDialog = new AlertDialog.Builder(BookListMainActivity.this)
                        .setTitle(R.string.string_confirmation)
                        .setMessage("请输入新" + name.substring(6) + "名")
                        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                for (String string : labels) {
                                    if (string.equals(editText.getText().toString())) {
                                        Toast.makeText(getApplicationContext(), "Can not rename label's name same with exist label!", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                }
                                int x = labels.indexOf(label);
                                navigationView.getMenu().getItem(3 + labels.indexOf(label)).setTitle("    " + editText.getText());
                                labels.remove(x);
                                labels.add(x, editText.getText().toString());
                                eachBookHash.forEach((key, value) -> {
                                    int[] temp = value.get(label);
                                    value.remove(label);
                                    value.put(editText.getText().toString(), temp);
                                });
                                HashMap temp = hashMaps.get(label);
                                hashMaps.remove(label);
                                hashMaps.put(editText.getText().toString(), temp);
                                label = editText.getText().toString().trim();
                                new DataSaver().saveLabel(getApplicationContext(), labels);
                                new DataSaver().saveHashMaps(getApplicationContext(), hashMaps);
                                new DataSaver().saveEachBook(getApplicationContext(), eachBookHash);
                            }
                        }).setView(editText)
                        .create();
                alertDialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void createMenu(NavigationView navigationView) {
        navigationView.setSelected(true);
        navigationView.setItemTextAppearance(R.style.BlackText);
        navigationView.getMenu().add(0, 100, 0, "    Books").setIcon(R.drawable.ic_bookshelf);
        navigationView.getMenu().add(0, 101, 0, "    Search").setIcon(R.drawable.ic_search);
        navigationView.getMenu().add(0, 105, 0, "    Search On Internet").setIcon(R.drawable.ic_website);
        navigationView.getMenu().add(1, 102, 50, "    Create new label").setIcon(R.drawable.ic_add);
        navigationView.getMenu().add(2, 103, 100, "    Settings").setIcon(R.drawable.ic_settings);
        navigationView.getMenu().add(2, 104, 100, "    About").setIcon(R.drawable.ic_about);
    }


    public void initEachBookHashMap() {
        eachBookHash = new DataSaver().LoadEachBook(getApplicationContext());
        String extStorageDirectory = Environment.getExternalStorageState().toString();
        extStorageDirectory = Environment.getExternalStorageDirectory().toString();

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请权限
//                    requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_CODE_CALL_PHONE);
            ActivityCompat.requestPermissions(BookListMainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

        for (int i = 0; i < mArray.size(); i++) {
            Resources res = this.getResources();
            try {
                BitmapDrawable d = (BitmapDrawable) res.getDrawable(mArray.get(i));
                Bitmap img = d.getBitmap();
                String path = extStorageDirectory + "/Pictures/book" + i + ".jpg";
                OutputStream os = new FileOutputStream(path);
                img.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.close();
            } catch (Exception e) {
                Log.e("TAG", "", e);
            }
        }
        bookCoverNumber = new DataSaver().loadBookCoverNumber(getApplicationContext());
    }

    public void initLabels() {
        label = "default";
        labels = new DataSaver().LoadLabel(getApplicationContext());
        for (String string : labels) {
            navigationView.getMenu().add(1, string.hashCode(), 0, "    " + string).setIcon(R.drawable.ic_label);
        }
        hashMaps = new DataSaver().LoadHashMaps(getApplicationContext());
    }
}